const fs = require('fs')
const TronWeb = require('tronweb')
const config = require('./config')
const utils = require('./utils')

async function main(argv) {
  const secret = argv[2]
  const offset = Number(argv[3])
  const limit = Number(argv[4])
  const stateFile = argv[5]
  const tronWeb = new TronWeb(
    config.providers.fullNode,
    config.providers.solidityNode,
    config.providers.eventServer,
    secret
  )
  const contract = await tronWeb.contract().at(config.contractId)
  const state = JSON.parse(fs.readFileSync(stateFile))
  const allPixels = state.pixels

  let failedBundles = []
  let i = offset
  let buyPixels = []
  let totalPrice = 0
  while (i < offset + limit && i < allPixels.length) {
    while (buyPixels.length < 10 && i < offset + limit && i < allPixels.length) {
      const p = allPixels[i++]
      if (p.price <= 20000000) {
        buyPixels.push(p)
        totalPrice += (p.price * 1.35)
      }
    }
    let params = []
    for (let p of buyPixels) {
      params.push(p.coordinate)
      params.push(p.color)
    }
    console.log(`buying pixels:`, params.toString(), totalPrice)
    try {
      let result = await contract.buyPixels(params).send({
        shouldPollResponse: false,
        callValue: totalPrice
      })
      console.log('success count:', result)
    } catch (e) {
      console.log('failed to buy:', e)
      failedBundles.push(buyPixels)
    }
    await utils.sleep(500)
    
    buyPixels = []
    totalPrice = 0
  }
  console.log('=======================All pixels failed======================================')
  console.log(utils.prettyJson(failedBundles))
}

main(process.argv).then().catch(console.log)
